import logging
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status, Query, File, UploadFile
from fastapi.responses import JSONResponse
from sqlalchemy.orm import Session
from models import Product, Category, ProductView, Favorite
from database import get_db
from schemas import (
    ProductResponse, 
    ProductCreate, 
    ProductUpdate, 
    PaginatedResponse,
    BaseResponse,
    ImageUploadResponse,
    CategoryListResponse
)
import os
import uuid
from pathlib import Path
import aiofiles
from config import settings
# 简单的用户类型定义，用于依赖注入
class User:
    def __init__(self, id: int):
        self.id = id

def get_current_active_user():
    # 暂时返回一个模拟用户，后续需要从认证中获取真实用户
    return User(id=1)

router = APIRouter()

# 配置日志
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

# 确保特定的路由在通配符路由之前定义

@router.get("/test")
async def test_route():
    """测试路由"""
    logger.debug("Test route accessed")
    print("Test route accessed")
    return {"message": "Test route works"}

@router.get("/simple-test")
async def simple_test_route():
    """简单测试路由"""
    return {"message": "Simple test route works"}

@router.get("/categories", response_model=CategoryListResponse)
async def get_categories(db: Session = Depends(get_db)):
    """获取分类列表"""
    try:
        logger.debug("Fetching categories from database...")
        print("Fetching categories from database...")
        categories = db.query(Category).filter(Category.is_active == True).all()
        logger.debug(f"Fetched {len(categories)} categories.")
        print(f"Fetched {len(categories)} categories.")
        for category in categories:
            logger.debug(f"Category: {category.name}, icon_url: {category.icon_url}")
            print(f"Category: {category.name}, icon_url: {category.icon_url}")
        return CategoryListResponse(data=categories)
    except Exception as e:
        logger.error(f"Error fetching categories: {str(e)}")
        print(f"Error fetching categories: {str(e)}")
        raise

@router.get("/recommend", response_model=PaginatedResponse)
async def get_recommended_products(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(12, ge=1, le=50, description="每页数量"),
    db: Session = Depends(get_db)
):
    """获取推荐商品（简单实现：按创建时间排序的最新商品）"""
    query = db.query(Product).filter(
        Product.status == 'available'
    )
    
    # 排序：最新创建的商品在前
    query = query.order_by(Product.created_at.desc())
    
    # 分页
    total = query.count()
    products = query.offset((page - 1) * size).limit(size).all()
    
    return PaginatedResponse(
        items=products,
        total=total,
        page=page,
        size=size,
        pages=(total + size - 1) // size
    )

@router.get("/{product_id:int}", response_model=ProductResponse)
async def get_product(
    product_id: int,
    db: Session = Depends(get_db)
):
    """获取商品详情"""
    product = db.query(Product).filter(Product.id == product_id).first()
    if not product:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="商品不存在"
        )
    
    # 记录商品浏览
    product_view = ProductView(product_id=product_id)
    db.add(product_view)
    db.commit()
    
    return product

@router.get("/", response_model=PaginatedResponse)
async def get_products(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=100, description="每页数量"),
    category_id: Optional[int] = Query(None, description="分类ID"),

    keyword: Optional[str] = Query(None, description="搜索关键词"),
    min_price: Optional[float] = Query(None, ge=0, description="最低价格"),
    max_price: Optional[float] = Query(None, ge=0, description="最高价格"),
    condition: Optional[str] = Query(None, description="商品状态"),
    seller_id: Optional[int] = Query(None, description="卖家ID"),
    db: Session = Depends(get_db)
):
    """获取商品列表（分页）"""
    query = db.query(Product).filter(Product.status == 'available')
    
    # 分类筛选
    if category_id:
        query = query.filter(Product.category_id == category_id)
    
    # 校区筛选

    
    # 关键词搜索
    if keyword:
        query = query.filter(
            (Product.name.contains(keyword)) |  # 使用name而不是title
            (Product.description.contains(keyword))
        )
    
    # 价格筛选
    if min_price is not None:
        query = query.filter(Product.price >= min_price)
    if max_price is not None:
        query = query.filter(Product.price <= max_price)
    
    # 商品状态筛选
    if condition:
        query = query.filter(Product.condition == condition)
    
    # 卖家筛选
    if seller_id:
        query = query.filter(Product.seller_id == seller_id)
    
    # 按创建时间倒序排列
    query = query.order_by(Product.created_at.desc())
    
    # 分页
    total = query.count()
    products = query.offset((page - 1) * size).limit(size).all()
    
    return PaginatedResponse(
        items=products,
        total=total,
        page=page,
        size=size,
        pages=(total + size - 1) // size
    )

@router.post("/", response_model=ProductResponse)
async def create_product(
    product_data: ProductCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """创建商品"""
    # 验证分类是否存在
    category = db.query(Category).filter(Category.id == product_data.category_id).first()
    if not category:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="指定的分类不存在"
        )
    
    # 创建商品
    product = Product(
        name=product_data.title,  # 使用name字段但接收title数据
        description=product_data.description,
        price=product_data.price,
        condition=product_data.condition,
        category_id=product_data.category_id,

        contact_method=product_data.contact_method,
        location=product_data.location if hasattr(product_data, 'location') else None,
        user_id=current_user.id,
        images=product_data.images if hasattr(product_data, 'images') else None,
        status='available'
    )
    
    db.add(product)
    db.commit()
    db.refresh(product)
    
    return product

@router.put("/{product_id}", response_model=ProductResponse)
async def update_product(
    product_id: int,
    product_data: ProductUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """更新商品信息"""
    product = db.query(Product).filter(Product.id == product_id).first()
    if not product:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="商品不存在"
        )
    
    # 检查权限
    if product.seller_id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权修改此商品"
        )
    
    # 检查商品状态
    if product.status != 'available':
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="商品状态不允许修改"
        )
    
    # 更新商品信息
    update_data = product_data.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(product, field, value)
    
    db.commit()
    db.refresh(product)
    
    return product

@router.delete("/{product_id}", response_model=BaseResponse)
async def delete_product(
    product_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """删除商品"""
    product = db.query(Product).filter(Product.id == product_id).first()
    if not product:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="商品不存在"
        )
    
    # 检查权限
    if product.seller_id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权删除此商品"
        )
    
    # 检查是否有未完成的交易
    from models import Trade
    active_trades = db.query(Trade).filter(
        Trade.product_id == product_id,
        Trade.status.in_(['pending_payment', 'paid', 'shipped'])
    ).count()
    
    if active_trades > 0:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="商品存在未完成的交易，无法删除"
        )
    
    # 软删除商品
    product.status = 'deleted'
    db.commit()
    
    return BaseResponse(message="商品删除成功")

@router.post("/{product_id}/favorite", response_model=BaseResponse)
async def add_favorite(
    product_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """收藏商品"""
    product = db.query(Product).filter(
        Product.id == product_id,
        Product.status == 'available'
    ).first()
    if not product:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="商品不存在"
        )
    
    # 检查是否已收藏
    existing_favorite = db.query(Favorite).filter(
        Favorite.user_id == current_user.id,
        Favorite.product_id == product_id
    ).first()
    
    if existing_favorite:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="已收藏此商品"
        )
    
    # 添加收藏
    favorite = Favorite(user_id=current_user.id, product_id=product_id)
    db.add(favorite)
    db.commit()
    
    return BaseResponse(message="收藏成功")

@router.delete("/{product_id}/favorite", response_model=BaseResponse)
async def remove_favorite(
    product_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """取消收藏"""
    favorite = db.query(Favorite).filter(
        Favorite.user_id == current_user.id,
        Favorite.product_id == product_id
    ).first()
    
    if not favorite:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="未收藏此商品"
        )
    
    db.delete(favorite)
    db.commit()
    
    return BaseResponse(message="取消收藏成功")

@router.delete("/{product_id}/delete", response_model=BaseResponse)
async def delete_product(
    product_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """删除商品"""
    # 检查商品是否存在
    product = db.query(Product).filter(Product.id == product_id).first()
    if not product:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="商品不存在"
        )
    
    # 检查权限（只有商品所有者可以删除）
    if product.seller_id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权删除此商品"
        )
    
    # 检查商品是否有进行中的交易
    active_trades = db.query(Trade).filter(
        Trade.product_id == product_id,
        Trade.status.in_(['pending_payment', 'paid', 'shipped'])
    ).count()
    
    if active_trades > 0:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="商品有进行中的交易，无法删除"
        )
    
    # 删除商品
    db.delete(product)
    db.commit()
    
    return BaseResponse(message="商品删除成功")

@router.post("/upload-image")
async def upload_image(
    image: UploadFile = File(...),
    current_user: User = Depends(get_current_active_user)
):
    """上传商品图片"""
    
    # 验证文件类型
    if not image.content_type or not image.content_type.startswith('image/'):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="只允许上传图片文件"
        )
    
    # 验证文件大小
    content = await image.read()
    file_size = len(content)
    
    if file_size > settings.MAX_FILE_SIZE:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"文件大小不能超过 {settings.MAX_FILE_SIZE // (1024 * 1024)}MB"
        )
    
    # 创建上传目录
    upload_dir = Path(settings.UPLOAD_DIR)
    upload_dir.mkdir(exist_ok=True)
    
    # 生成唯一文件名
    file_extension = Path(image.filename).suffix.lower()
    if file_extension not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="只允许上传 JPG、PNG、GIF、WebP 格式的图片"
        )
    
    unique_filename = f"{uuid.uuid4().hex}{file_extension}"
    file_path = upload_dir / unique_filename
    
    # 保存文件
    async with aiofiles.open(file_path, 'wb') as f:
        await f.write(content)
    
    # 返回文件URL
    image_url = f"/{settings.UPLOAD_DIR}/{unique_filename}"
    
    return {
        "success": True,
        "message": "图片上传成功",
        "image_url": unique_filename  # 只返回文件名，不包含路径前缀
    }